import Vuex from 'vuex'
import Vue from 'vue'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0,
    todos: [{
        id: 0,
        text: 'This is first massage!!!',
        done: true
      },
      {
        id: 1,
        text: 'Mybe this is a secend massage!!!',
        done: false
      }
    ]
  },
  getters: {
    doneTodos: state => {
      return state.todos.filter(todo => todo.done)
    },
    doneTodosCount: (state, getters) => {
      return getters.doneTodos.length
    }
  },
  mutations: {
    increment(state) {
      state.count++
    },
    addTodo(state, payload) {
      state.todos.push(payload)
    },
    removeTodo(state, id) {
      for (let i = 0; i < state.todos.length; i++) {
        let todo = state.todos[i]
        if (todo.id == id) {
          todo.done = false
          break
        }
      }
    }
  },
  actions: {
    async rmTodoAsync({
      commit
    }, id) {
      const time = () => new Promise((res, rej) => setTimeout(() => res(id), 200))
      commit('removeTodo', await time())
    }
  },
  strict: process.env.NODE_ENV !== 'production'
})
